package com.ysstech.reportworld.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.PropertyPreFilters;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysstech.common.cache.RedisCacheManager;
import com.ysstech.common.entity.Dicvalue;
import com.ysstech.common.entity.PageBean;
import com.ysstech.common.enums.YssEnum;
import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.service.DicvalueService;
import com.ysstech.common.util.DateUtil;
import com.ysstech.common.util.StringUtil;
import com.ysstech.common.util.fileutil.FileUtil;
import com.ysstech.reportworld.entity.*;
import com.ysstech.reportworld.enums.ReportWorldEnum;
import com.ysstech.reportworld.enums.ReportWorldStatusEnum;
import com.ysstech.reportworld.mapper.DemandBugInfoMapper;
import com.ysstech.reportworld.service.DemandBugInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 报表世界需求bug信息表 服务实现类
 * </p>
 *
 * @author lishuangliang
 * @since 2022-12-27
 */
@Service
public class DemandBugInfoServiceImpl extends ServiceImpl<DemandBugInfoMapper, DemandBugInfo> implements DemandBugInfoService {
    @Autowired
    private DicvalueService dicvalueService;
    @Autowired
    private DemandBugInfoMapper demandBugInfoMapper;
    @Autowired
    private RedisCacheManager redisCacheManager;

    /**
     * 获取需求BUG信息
     *
     * @param demandBugInfo
     * @param pageBean
     * @return
     * @throws Exception
     */
    public PageBean<DemandBugInfo> queryAllDemandBugInfo(DemandBugInfo demandBugInfo, PageBean pageBean) throws Exception {
        QueryWrapper<DemandBugInfo> wrapper = this.getQueryWrapper(demandBugInfo);
        IPage pageScheduleLog = this.page(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), wrapper);
        this.switchedListDemandBugInfo(pageScheduleLog.getRecords());
        return new PageBean<>(pageScheduleLog);
    }

    /**
     * 处理查询条件信息
     *
     * @param demandBugInfo
     * @return
     */
    private QueryWrapper<DemandBugInfo> getQueryWrapper(DemandBugInfo demandBugInfo) throws Exception {
        QueryWrapper<DemandBugInfo> wrapper = new QueryWrapper<>();
        if (null == demandBugInfo) {
            return wrapper;
        }
        if (StringUtils.isNotBlank(demandBugInfo.getVersion())) {
            wrapper.eq("VERSION", demandBugInfo.getVersion());
        }
        if (null != demandBugInfo.getStatus()) {
            wrapper.eq("STATUS", demandBugInfo.getStatus());
        }
        if (null != demandBugInfo.getDemandBugType()) {
            wrapper.eq("DEMAND_BUG_TYPE", demandBugInfo.getDemandBugType());
        }
        if (StringUtils.isNotBlank(demandBugInfo.getDemandBugNum())) {
            wrapper.like("DEMAND_BUG_NUM", demandBugInfo.getDemandBugNum());
        }
        if (StringUtils.isNotBlank(demandBugInfo.getStartDate()) && StringUtils.isNotBlank(demandBugInfo.getEndDate())) {
            wrapper.between("DEMAND_BUG_DATE", DateUtil.strToLocalDate(demandBugInfo.getStartDate()),
                    DateUtil.strToLocalDate(demandBugInfo.getEndDate()));
        }
        return wrapper;
    }

    /**
     * 类型，机构等中文的转换
     *
     * @param list
     * @return
     * @throws Exception
     */
    private List<DemandBugInfo> switchedListDemandBugInfo(List<DemandBugInfo> list) throws Exception {
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        //状态
        Map<String, String> mapStatus = dicvalueService.getCacheDicValueMap(ReportWorldEnum.REPORT_STATUS.getCode());
        for (DemandBugInfo demandBugInfo : list) {
            if (null == demandBugInfo) {
                continue;
            }
            //状态
            if (null != mapStatus && mapStatus.containsKey(String.valueOf(demandBugInfo.getStatus()))) {
                demandBugInfo.setStrStatus(mapStatus.get(String.valueOf(demandBugInfo.getStatus())));
            }
        }
        return list;
    }

    /**
     * 通过数据id和类型查询对应的需求BUG信息
     *
     * @param dataId
     * @param dataCode
     * @return
     */
    public List<DemandBugInfo> selectByPrimaryByDataId(String dataId, String dataCode) throws Exception {
        if (StringUtils.isBlank(dataId) || StringUtils.isBlank(dataCode)) {
            throw new BusinessException("获取数据对应的需求BUG信息失败，请稍后重试！");
        }
        Map<String, String> map = new HashMap<>();
        map.put("dataId", dataId);
        map.put("dataCode", dataCode);
        List<DemandBugInfo> list = demandBugInfoMapper.selectByPrimaryByDataId(map);
        this.switchedListDemandBugInfo(list);
        return list;
    }

    /**
     * 获取当前年份版本号的所有需求和BUG
     *
     * @return
     * @throws Exception
     */
    public List<DemandBugInfo> selectByPrimaryByVersion() throws Exception {
        QueryWrapper<DemandBugInfo> wrapper = new QueryWrapper<>();
        // 获取现在最大的版本号
        List<Dicvalue> listVersion = dicvalueService.getCacheDicValueList(ReportWorldEnum.REPORT_VERSION.getCode());
        if (CollectionUtils.isEmpty(listVersion)) {
            throw new BusinessException("没有获取到版本号，请稍后重试！");
        }
        List<String> list = new ArrayList<>();
        for (Dicvalue dicvalue : listVersion) {
            if (null == dicvalue || StringUtils.isBlank(dicvalue.getValue())
                    || !StringUtil.oneOf(dicvalue.getValue(), DateUtil.getSysYear(new Date()))) {
                continue;
            }
            list.add(dicvalue.getValue());
        }
        wrapper.in("VERSION", list);
        List<DemandBugInfo> listDemandBugInfo = this.list(wrapper);
        return listDemandBugInfo;
    }

    /**
     * 需求BUG数据的json
     *
     * @return
     * @throws Exception
     */
    public String getDemandBugJsonInfo() throws Exception {
        // 获取修改记录信息文件 取当前版本号的数据
      /*  String version = dicvalueService.getMaxValue(ReportWorldEnum.REPORT_VERSION.getCode());
        if (StringUtils.isBlank(version)) {
            throw new BusinessException("没有获取到版本号，请稍后重试！");
        }*/
        // 当前版本的需求BUG文件
        QueryWrapper<DemandBugInfo> demandBugInfoQueryWrapper = new QueryWrapper<>();
        // demandBugInfoQueryWrapper.eq("VERSION", version);
        demandBugInfoQueryWrapper.in("STATUS", ReportWorldStatusEnum.getUpgradeToolsZipStatus());
        List<DemandBugInfo> demandBugInfoList = this.list(demandBugInfoQueryWrapper);
        String[] includeProperties = {"id", "demandBugNum", "demandBugType", "demandBugDate", "description", "version", "status"};
        PropertyPreFilters filters = new PropertyPreFilters();
        PropertyPreFilters.MySimplePropertyPreFilter includefilter = filters.addFilter();
        includefilter.addIncludes(includeProperties);
        return JSONObject.toJSONString(demandBugInfoList, includefilter, SerializerFeature.WriteMapNullValue);
    }

    /**
     * 从项目管理计划文件中读取当前版本的需求
     *
     * @param multipartfile
     * @return
     */
    public String readDemandBugInfo(MultipartFile multipartfile) throws Exception {
        if (null == multipartfile) {
            throw new BusinessException("没有获取到文件，请稍后重试！");
        }
        String fileName = multipartfile.getOriginalFilename();
        fileName = fileName.substring(0, fileName.lastIndexOf("."));
        if (!StringUtil.oneOf(fileName, "需求,BUG")) {
            throw new BusinessException("请选择正确的需求或者BUG模板文件！");
        }
        List<List<Object>> listData = FileUtil.readerExcelObj(FileUtil.MultipartFileToFile(multipartfile));
        // 获取现在最大的版本号
        String version = dicvalueService.getMaxValue(ReportWorldEnum.REPORT_VERSION.getCode());
        if (StringUtils.isBlank(version)) {
            throw new BusinessException("没有获取到版本号，请稍后重试！");
        }
        if (CollectionUtils.isEmpty(listData) || listData.size() == 1) {
            throw new BusinessException("没有获取到文件的内容，请稍后重试！");
        }
        List<DemandBugInfo> list = new ArrayList<>();
        StringBuffer buffer = new StringBuffer();
        for (int i = 1; i < listData.size(); i++) {
            List<Object> objectList = listData.get(i);
            if (CollectionUtils.isEmpty(objectList)) {
                continue;
            }
            Object demandBugNum = objectList.get(0); // 需求编号
            Object description = objectList.get(1);// 需求描述
            Object demandBugDate = objectList.get(2);// 需求发布时间
            if (null == demandBugNum) {
                throw new BusinessException("没有获取到需求编号，请补充完整！");
            }
            if (null == description) {
                throw new BusinessException("没有获取到需求描述信息，请补充完整！");
            }
            if (null == demandBugDate) { // 发布日期为空
                throw new BusinessException("没有获取到需求预计发布日期，请补充完整！");
            }

            // 查询是不是已经存在
            QueryWrapper<DemandBugInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("DEMAND_BUG_NUM", demandBugNum.toString());
            DemandBugInfo info = this.getOne(wrapper);
            if (null != info) {
                buffer.append("【" + demandBugNum.toString() + "】").append(StringUtil.oneOf(fileName, "需求") ? "需求" : "BUG")
                        .append("已经存在,将被删除替换成最新的，请确认！").append("\r\n");
                this.remove(wrapper);
            }
            DemandBugInfo demandBugInfo = new DemandBugInfo();
            demandBugInfo.setId(DateUtil.generateUUID());
            demandBugInfo.setDemandBugNum(demandBugNum.toString());
            demandBugInfo.setDescription(description.toString());
            Date date = DateUtil.strToDateByFormat(demandBugDate.toString(), YssEnum.YSS_DEFAULT_DATE_TIME.getCode());
            demandBugInfo.setDemandBugDate(DateUtil.strToLocalDate(DateUtil.dateToStr(date)));
            demandBugInfo.setDemandBugFsource(1);
            if (objectList.size() > 3) {
                Object demandBugFsource = objectList.get(3);// 来源
                if (null != demandBugFsource && "内部".equals(demandBugFsource.toString())) {
                    demandBugInfo.setDemandBugFsource(2);
                }
            }
            demandBugInfo.setAddUser(redisCacheManager.getLoginUserInfo().getLoginId());
            demandBugInfo.setAddTime(LocalDateTime.now());
            demandBugInfo.setStatus(ReportWorldStatusEnum.REPORT_NORMAL.getCode());
            demandBugInfo.setVersion(version);
            if (StringUtil.oneOf(fileName, "需求")) {
                demandBugInfo.setDemandBugType(1); // 需求
            } else {
                demandBugInfo.setDemandBugType(2); // BUG
            }
            list.add(demandBugInfo);
        }
        if (!CollectionUtils.isEmpty(list)) {
            this.saveBatch(list);
        }
        buffer.append("成功读取").append(StringUtil.oneOf(fileName, "需求") ? "需求" : "BUG").append("数" + (list.size()) + "条").append("\r\n");
        return buffer.toString();
    }

}
